//
//  QSPayTool.swift
//  TestSwift
//
//  Created by Song on 2018/7/5.
//  Copyright © 2018年 Song. All rights reserved.
//

import UIKit

/// 支付类型
enum QSPayType {
    case aliPay     // 支付宝支付
    case wechatPay  // 微信支付
}

class QSPayTool: NSObject, WXApiDelegate {
    // 微信支付的回调
    var weChatPaySuccess: (() -> (Void))?
    var weChatPayFailed: (() -> (Void))?
    var weChatPayCancel: (() -> (Void))?
    
    // 单例
    static var share : QSPayTool {
        struct Static {
            static let instance : QSPayTool = QSPayTool()
        }
        return Static.instance
    }
    
    /// 注册微信appId
    /// 调用微信支付前要先注册，一般在AppDelegate中注册
    func qs_registerWeCharAppId(_ appId: String) {
        WXApi.registerApp(appId)
    }
    
    /// 微信支付回调
    func qs_weChatHandleOpenUrl(_ url: URL) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }
    
    /// 支付
    ///
    /// - Parameters:
    ///   - type: 支付类型
    ///   - payData: 后台返回的支付数据
    ///   - success: 成功
    ///   - failed: 失败
    ///   - cancel: 取消
    func qs_pay(type: QSPayType, payData: String, success: @escaping (() -> (Void)), failed: @escaping (() -> (Void)), cancel: @escaping (() -> (Void))) {
        switch type {
        case .aliPay:   // 支付宝
            AlipaySDK.defaultService().payOrder(payData, fromScheme: "自定的本APP的scheme") { (result) in
                let resultDic = result as! Dictionary<String, Any>
                
                let resultCodeStr = resultDic["resultStatus"] as! NSString
                let resultCode = resultCodeStr.integerValue
                
                switch resultCode {
                case 9000:// success
                    success()
                    
                case 6001:// cancle pay
                    cancel()
                    
//                case 8000:// handling
//                case 6004:// Unknow
//                case 4000:// payfail
//                case 5000:// Re request
//                case 6002://connect fail
                    
                    default:
                        failed()
                }
            }
            
        case .wechatPay:
            if WXApi.isWXAppInstalled() {
                let jsonData = payData.data(using: .utf8)
                let dataDict = try? JSONSerialization.jsonObject(with: jsonData!, options: JSONSerialization.ReadingOptions.mutableLeaves)
                if dataDict == nil {
                    return
                }
                
                // 回调
                self.weChatPaySuccess = success
                self.weChatPayFailed = failed
                self.weChatPayCancel = cancel
                
                let payReq = PayReq.init()
                payReq.nonceStr = (dataDict as! Dictionary)["noncestr"]     // 随机串，防重发
                payReq.package = (dataDict as! Dictionary)["package"]       // 商家根据财付通文档填写的数据和签名
                payReq.partnerId = (dataDict as! Dictionary)["partnerid"]   // 商家向财付通申请的商家id
                payReq.prepayId = (dataDict as! Dictionary)["prepayid"]     // 预支付订单
                payReq.sign = (dataDict as! Dictionary)["sign"]             // 商家根据微信开放平台文档对数据做的签名
                payReq.timeStamp = (dataDict as! Dictionary)["timestamp"]!  // 时间戳，防重发
                
                WXApi.send(payReq)
            } else {
                QSHud.qs_showText(title: "请先安装微信！")
            }
        }
    }
    
    // MARK: - WXApiDelegate
    func onResp(_ resp: BaseResp!) {
        if resp is PayResp {
            let response = resp as! PayResp
            
            switch response.errCode {
            case WXSuccess.rawValue:
                if self.weChatPaySuccess != nil {
                    self.weChatPaySuccess!()
                }
                
            case WXErrCodeUserCancel.rawValue:
                if self.weChatPayCancel != nil {
                    self.weChatPayCancel!()
                }
                
            default:
                if self.weChatPayFailed != nil {
                    self.weChatPayFailed!()
                }
            }
        }
    }
}
